package controller;

import common.action.SaveProductAction;
import common.domain.Product;
import common.form.ProductForm;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 实现了Controller 接口的控制器类
 */
public class SaveProductController implements Controller {

    private static final Log logger = LogFactory.getLog(SaveProductController.class);

    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        logger.info("SaveProductController called....");
        httpServletRequest.setCharacterEncoding("UTF-8");
        // 接收前端数据
        ProductForm productForm = new ProductForm();
        productForm.setName(httpServletRequest.getParameter("name"));
        productForm.setDescription(httpServletRequest.getParameter("description"));
        productForm.setPrice(httpServletRequest.getParameter("price"));

        // 保存在领域对象
        Product product = new Product();
        product.setName(productForm.getName());
        product.setDescription(productForm.getDescription());
        try {
            product.setPrice(Float.parseFloat(productForm.getPrice()));
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        // 业务操作
        SaveProductAction saveProductAction = new SaveProductAction();
        saveProductAction.save(product);

        // 配置了视图解析器
        return new ModelAndView("ProductDetail", "product", product);
    }
}
